package com.hankol.community

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.Configuration
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.BaseConstant
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.CommentEnum
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.chad.library.adapter.base.BaseQuickAdapter
import com.okhttp.comment.CommentBean
import com.hankol.community.adapter.DynamicSearchTopicTabAdapter
import com.hankol.community.adapter.PulClassroomAdapter
import com.hankol.community.adapter.PulVideoTabAdapter
import com.hankol.community.api.CommunityConstant
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.PulCourseBean
import com.hankol.community.databinding.ActivityPulpitVideoBinding
import com.hankol.community.fragment.PulVideoCommentFragment
import com.hankol.community.fragment.PulpitHomeInfoFragment
import com.hankol.community.view.HKVideoView
import com.hankol.community.viewmodel.PulpitViewModel
import com.liaoinstan.springview.widget.SpringView
import com.like.LikeButton
import com.like.OnLikeListener
import com.okhttp.comment.CommentConstant
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * @description 讲坛视频页
 * @author 关忆北、
 * @time 2022/5/5 10:37 上午
 */
@Route(path = ActivityRouter.COMMUNITY.COMMUNITY_PULPIT_VIDEO)
class PulCourseActivity : BaseActivity(), HKVideoView.OnVideoPlayListener, View.OnClickListener {
    private var pulCourseId: Int = 0//课程id
    private var pulpitId: Int = 0//讲坛id
    public var videoPos: Int = -1
    private var pager: Int = 1
    private var selectPos: Int = -1
    private var studySpeed: Long = 0
    private val mTableName = mutableListOf("详情")
    private var mFragment: ArrayList<Fragment> = ArrayList()
    private lateinit var mAdapter: PulClassroomAdapter
    private lateinit var mPulVideoTabAdapter: PulVideoTabAdapter
    private lateinit var mViewModel: PulpitViewModel
    private lateinit var mDataBinding: ActivityPulpitVideoBinding
    private lateinit var mPulpitHomeInfoFragment: PulpitHomeInfoFragment
    private lateinit var mPulVideoCommentFragment: PulVideoCommentFragment
    private var mCommentBean: CommentBean.DataBean? = null
    private var mPulCourseBean: PulCourseBean? = null
    private var mShowSharePop: SharePopupWindow? = null
    private var mSpeed: Long = 0
    private var mTotalSpeed: Long = 0
    val communityHelp: CommunityHelp =
            ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)

    override fun getLayoutId(): Int {

        return R.layout.activity_pulpit_video
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setFormPagePos("视频")
        mDataBinding = getDataBinding<ActivityPulpitVideoBinding>()
        mViewModel = getActivityViewModelProvider(this).get(PulpitViewModel::class.java)
        mViewModel.upBarHeight(mDataBinding.viewNavigation, this)
        intent.extras?.let {
            if (ARouterUtils.parseParams(it, CommunityConstant.PUL_COURSE_ID)[0].checkNotNull()) {
                pulCourseId =
                        ARouterUtils.parseParams(it, CommunityConstant.PUL_COURSE_ID)[0].toInt()
            }
            if (ARouterUtils.parseParams(it, CommunityConstant.PULPIT_ID)[0].checkNotNull()) {
                pulpitId = ARouterUtils.parseParams(it, CommunityConstant.PULPIT_ID)[0].toInt()
            }

            mPulpitHomeInfoFragment = PulpitHomeInfoFragment()
            mPulVideoCommentFragment = PulVideoCommentFragment(communityHelp)
            mFragment.add(mPulpitHomeInfoFragment)
            mFragment.add(mPulVideoCommentFragment)

            mAdapter = PulClassroomAdapter(this, pulCourseId)
            mPulVideoTabAdapter = PulVideoTabAdapter()
            val dynamicSearchTopicTabAdapter = DynamicSearchTopicTabAdapter(supportFragmentManager)

            mDataBinding.rvPulpitVideoClassroom.adapter = mAdapter
            mDataBinding.rvTabPulVideo.adapter = mPulVideoTabAdapter
            mDataBinding.vpPulpitVideo.adapter = dynamicSearchTopicTabAdapter

            dynamicSearchTopicTabAdapter.setEmptyTitleFragment(mFragment)

            loadData()
            initObserve()
            initListener()
        }
    }

    fun loadData() {
        mDataBinding.tvPulpitVideoTitle.paint.isFakeBoldText = true
        mDataBinding.ivPulVideoTopTitle.paint.isFakeBoldText = true

        mDataBinding.includePulVideoComment.llCommentGive.visibility = View.GONE
        mDataBinding.includePulVideoComment.llCommentCollection.visibility = View.VISIBLE
        mDataBinding.includePulVideoComment.llShare.visibility = View.VISIBLE
        mDataBinding.smartPulpitVideo.header = SpringViewNewHeader(applicationContext)
        mDataBinding.smartPulpitVideo.footer = SpringViewNewFooter(applicationContext)
        mDataBinding.smartPulpitVideo.type = SpringView.Type.FOLLOW
        mPulVideoCommentFragment.setBinding(mDataBinding)

        mViewModel.reqPulCourse(pulCourseId.toLong())
        mViewModel.reqPulpitList(pulpitId.toLong())//拉取视频列表数据
    }

    @SuppressLint("SetTextI18n")
    private fun initObserve() {
        //评论列表
        mViewModel.commentListLiveData.observe(this, Observer {
            mDataBinding.smartPulpitVideo.onFinishFreshAndLoad()
            if (it != null) {
                mCommentBean = it
                mDataBinding.includePulVideoComment.tvCommentComCount.text =
                        if (it.totalCount == 0) "抢首评" else NumberUtils.formatBigNum(it.totalCount.toString())
                mPulVideoCommentFragment.setData(pager, it)
                pager++
            }
        })

        //讲坛课程列表
        mViewModel.pulpitListLD.observe(this, Observer {
            mDataBinding.smartPulpitVideo.onFinishFreshAndLoad()
            if (it.checkNotNull() && it.data.checkNotNull()) {
                mAdapter.setNewData(it.data)
                mDataBinding.tvPulpitVideoClassroom.text = "（共${it.data!!.size}讲）"
            }
        })

        //讲坛课程详情
        mViewModel.forumCourseLD.observe(this, Observer {
            mDataBinding.smartPulpitVideo.onFinishFreshAndLoad()
            if (it != null) {
                pager = 1//初始化评论列表分页
                mPulCourseBean = it
                pulCourseId = it.id.toInt()
                mPulVideoCommentFragment.setPulCourseId(it.id)
                mViewModel.reqCommentList(pager, it.id, 0)
                mViewModel.upBottomNum(mDataBinding, it)

                //移除已经存在评论的数据。切换不同课程情况下触发
                if (mTableName.size == 2) mTableName.removeAt(1)
                mTableName.add(if (it.commentNum > 0) "评论（${it.commentNum}）" else "评论")
                mPulVideoTabAdapter.setNewData(mTableName)

                mViewModel.initPlayerViewState(mDataBinding)

                mDataBinding.tvPulpitVideoTitle.text = it.title
                mDataBinding.ivPulVideoTopTitle.text = it.title

                mDataBinding.includePulVideoComment.ivCommentConState.isLiked = it.favorited == 1

                mDataBinding.tvPulpitVideoAuthorName.text = ColorTextUtils.substringDes(it.lecturer, 4)

                mPulpitHomeInfoFragment.setVideoInfoView(CommunityConstant.PULPIT_HOME_INFO, it)
                GlideUtils.loadUserHead(applicationContext, it.lecturerIcon, mDataBinding.circlePulpitVideoHead)
                mDataBinding.hkPulpitVideo.keepScreenOn=true
                mDataBinding.hkPulpitVideo.startVideo(this, mViewModel.getHKVideoConfig(mDataBinding, it.offset), it.url, this)
                mDataBinding.tvPulpitVideoTime.text = "${TimeUtil.getRuleTime(it.ctime, "yyyy-MM-dd")} · " + "${NumberUtils.formatBigNum(it.watchNum.toString())}播放"
                mViewModel.reqStatistics(it.id)//统计观看次数
            }
        })

        mViewModel.friendLiveData.observe(this, Observer {
            mShowSharePop?.setShareFriendAdapter(mViewModel.changeFriend(it))
        })

        mViewModel.collectionLiveData.observe(this, Observer {
            if (it) EventBusUtils.sendNotify(MessageBus.msgId_collection_success)
        })
    }

    fun initListener() {
        mPulVideoTabAdapter.onItemClickListener =
                BaseQuickAdapter.OnItemClickListener { _, _, position ->
                    mDataBinding.vpPulpitVideo.currentItem = position
                    mPulVideoTabAdapter.setSelectPos(position)
                    selectPos = position
                }

        mDataBinding.vpPulpitVideo.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (selectPos != position) mPulVideoTabAdapter.setSelectPos(position)
                selectPos = position
            }

            override fun onPageScrollStateChanged(state: Int) {}

        })

        mAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            if (videoPos != position) {
                videoPos = position
                mDataBinding.hkPulpitVideo.pause()
                reqSaveProgress(mSpeed, mTotalSpeed)
                val pulpitListBean = mAdapter.data[position]
                mViewModel.reqPulCourse(pulpitListBean.id)
            }
        }

        mDataBinding.smartPulpitVideo.setListener(object : SpringView.OnFreshListener {
            override fun onRefresh() {
                pager = 1//初始化评论列表分页
                mViewModel.reqCommentList(pager, pulCourseId.toLong(), 0)
            }

            override fun onLoadmore() {
                mViewModel.reqCommentList(pager, pulCourseId.toLong(), 0)
            }

        })

        mDataBinding.ivPulVideoShare.setOnClickListener(this)
        mDataBinding.includePulVideoComment.llCommentSaySomething.setOnClickListener(this)
        mDataBinding.includePulVideoComment.llCommentJumpCom.setOnClickListener(this)
        mDataBinding.includePulVideoComment.llShare.setOnClickListener(this)

        mDataBinding.includePulVideoComment.ivCommentConState.setOnLikeListener(object :
                OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                mPulCourseBean?.let {
                    mViewModel.reqCollection(true, 3, it.id)
                }
            }

            override fun unLiked(likeButton: LikeButton?) {
                mPulCourseBean?.let {
                    mViewModel.reqCollection(false, 3, it.id)
                }
            }
        })
        mDataBinding.ivPulVideoBack.setOnClickListener { finish() }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏幕
            mDataBinding.viewNavigation.visibility = View.GONE
            mDataBinding.rlPulTitleBlock.visibility = View.GONE
            mDataBinding.includePulVideoComment.llBaseCommentBotView.visibility = View.GONE
            mDataBinding.rlPulTitleBlock.setBackgroundColor(resources.getColor(R.color.transparent))
        } else {
            //竖屏
            mDataBinding.viewNavigation.visibility = View.VISIBLE
            mDataBinding.rlPulTitleBlock.visibility = View.VISIBLE
            mDataBinding.includePulVideoComment.llBaseCommentBotView.visibility = View.VISIBLE
            mDataBinding.rlPulTitleBlock.setBackgroundColor(resources.getColor(R.color.white))
        }
    }

    override fun onPause() {
        super.onPause()
        reqSaveProgress(mSpeed, mTotalSpeed)
        mDataBinding.hkPulpitVideo.pause()
        mDataBinding.hkPulpitVideo.stopPlay()
    }

    override fun onDestroy() {
        mPulCourseBean?.let {
            mViewModel.noticeCourseCollection(it.favorited == 1)
        }
        super.onDestroy()
        mDataBinding.hkPulpitVideo.pause()
        mDataBinding.hkPulpitVideo.stopPlay()
        mDataBinding.hkPulpitVideo.clear()
        mPulCourseBean?.let {
            SensorsDataManager.instance.browseForumVideo(it.courseTopicTitle, it.forumTitle, it.title, studySpeed, SensorsDataManager.instance.getBrowseTime())
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val mCoursesBean: CommentBean.DataBean? = mPulVideoCommentFragment.activityResult(requestCode, resultCode, data, mCommentBean)
        if (requestCode == CommentConstant.COMMENT_REQUESTCODE && resultCode == CommentConstant.COMMENT_RESPONSE) {
            mCoursesBean?.let {
                this.mCommentBean = it
                //移除已经存在评论的数据。
                if (mTableName.size == 2) mTableName.removeAt(1)
                mTableName.add(if (it.totalCount <= 0) "评论" else "评论（${it.totalCount}）")
                mPulVideoTabAdapter.setNewData(mTableName)
                mPulCourseBean?.commentNum = it.totalCount
                mViewModel.upBottomNum(mDataBinding, mPulCourseBean)
            }
        }
    }

    override fun onPlayProgress(speed: Long, totalSpeed: Long) {
        //播放回执
        this.mSpeed = speed
        this.mTotalSpeed = totalSpeed
    }

    override fun onPlayComplete() {
        //播放完成
        mViewModel.reqSaveProgress(pulCourseId.toLong(), 0, 100)
    }

    override fun onReadyToPlay() {
        //准备播放
        mDataBinding.llPulVideoSpeed.visibility = View.VISIBLE
    }

    override fun onStudyListener(speed: Long, totalSpeed: Long) {
        reqSaveProgress(speed, totalSpeed)
    }

    override fun onHorizontalScreen() {
    }

    override fun onVerticalScreen() {
    }

    private fun reqSaveProgress(speed: Long, totalSpeed: Long) {
        //学习进度回执
        studySpeed = mViewModel.videoComputing((speed / 1000).toDouble(), (totalSpeed / 1000).toDouble())
        mViewModel.reqSaveProgress(pulCourseId.toLong(), if (speed == totalSpeed) 0 else speed, studySpeed)
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        when (messageBus.codeType) {
            MessageBus.msgId_share_success -> {
                mPulCourseBean?.let {
                    it.shareNum = it.shareNum + 1
                    mViewModel.upBottomNum(mDataBinding, it)
                }
            }
            MessageBus.msgId_collection_success -> {
                mPulCourseBean?.let {
                    it.favoriteNum =
                            if (mDataBinding.includePulVideoComment.ivCommentConState.isLiked) {
                                it.favorited = 1
                                ToastUtils.showShort(applicationContext, "收藏成功")
                                it.favoriteNum + 1

                            } else {
                                it.favorited = 0
                                ToastUtils.showShort(applicationContext, "取消收藏")
                                it.favoriteNum - 1
                            }
                    mViewModel.upBottomNum(mDataBinding, it)
                }
            }
        }

    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.iv_pul_video_share,
            R.id.ll_share -> {
                if (DoubleUtils.isFastDoubleClick()) return
                mPulCourseBean?.let {
                    mShowSharePop = mViewModel.showShare(mViewModel.pulCourseBean2showShare(it), this, communityHelp)
                    mViewModel.reqFriendList()
                }
            }
            R.id.ll_comment_saySomething -> {
                mPulCourseBean?.let {
                    //埋点
                    BaseConstant.loadCommentEventBusBean("讲坛视频", "内容详情页")
                    communityHelp.openCommentActivity(
                            this, CommentEnum.COMMENT_FORUM_COURSE.commentType,
                            it.id.toInt(), mDataBinding.includePulVideoComment.tvCommentSaySomething.text
                            .toString().trim(), "", false, CommentConstant.COMMENT_REQUESTCODE)
                }
            }
            R.id.ll_comment_jumpCom -> {
                mDataBinding.rvTabPulVideo.post { mDataBinding.scroPul.smoothScrollTo(0, mDataBinding.rvTabPulVideo.top) }
            }
        }
    }

}